package com.xuenci.gulimall.auth.controller;/*
 *@author:xec
 *@date:2022/5/22  20:56
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xuenci.common.utils.HttpUtils;
import com.xuenci.common.utils.R;
import com.xuenci.gulimall.auth.feign.MemberFeignService;
import com.xuenci.common.vo.MemberRespVo;
import com.xuenci.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * 处理社交登录请求
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletResponse servletResponse) throws Exception {
        Map<String, String> header = new HashMap<>();
        Map<String, String> query = new HashMap<>();
        header.put("Accept","application/json");
        header.put("Host","api.weibo.com");

        Map<String, String> map = new HashMap<>();
        /**
         map.put("code",code);
         * GitHub的验证是传到header里面的，微博的验证是在body里面
         * 这个是微博的
         */
        map.put("client_id","3228924161");
        map.put("client_secret","4d3617d0c79902bd9c2ee8203383dfbb");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);

        // 根据code换区accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), new HashMap<>(),map);
        if (response.getStatusLine().getStatusCode() == 200){
            // 获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            // 知道当前是哪个社交用户
            // 1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）
            // 登录或者注册这个用户
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode()==0){
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功:{}",data.toString());
                // 第一次使用session；命令浏览器保运卡号jsessionID这个cookie
                // 子域之间带上卡号 发卡的时候（指定域名为父域名），即使是子域系统发的卡也能让父域读到
                // TODO 1、默认发的令牌。session=“值是唯一字符串”。作用域：当前域（解决session共享问题）
                // TODO 2、使用JSON的序列化方式来序列化对象到redis中
                session.setAttribute("loginUser",data );
//                servletResponse.addCookie(new Cookie(""));
                // 登录成功就跳回首页
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
